package com.example.datadashboard.controller;

import com.example.datadashboard.common.Result;
import com.example.datadashboard.dto.PageResultDTO;
import com.example.datadashboard.dto.UserDTO;
import com.example.datadashboard.dto.UserQueryDTO;
import com.example.datadashboard.entity.User;
import com.example.datadashboard.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/list")
    public Result<PageResultDTO<UserDTO>> getUserList(@RequestBody UserQueryDTO queryDTO) {
        return Result.success(userService.queryUsers(queryDTO));
    }

    @GetMapping("/{id}")
    public Result<UserDTO> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setIdNumber(user.getIdNumber());
        dto.setPhone(user.getPhone());
        dto.setEmail(user.getEmail());
        dto.setStatus(user.getStatus());
        dto.setCreateTime(user.getCreateTime() != null ? user.getCreateTime().toString() : null);
        dto.setUpdateTime(user.getUpdateTime() != null ? user.getUpdateTime().toString() : null);
        dto.setSexy(user.getSexy());
        dto.setAddress(user.getAddress());
        dto.setRemark(user.getRemark());
        return Result.success(dto);
    }

    @PostMapping
    public Result<Boolean> save(@RequestBody User user) {
        return Result.success(userService.save(user));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody User user) {
        return Result.success(userService.updateById(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }

    @GetMapping("/export")
    public void export(UserQueryDTO queryDTO, HttpServletResponse response) {
        userService.exportUsers(response, queryDTO);
    }
}